
<%@ page import="java.util.Map" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>设备管理</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
        }

        body {
            min-height: 100vh;
            background: linear-gradient(135deg, #f8faf6 0%, #e6f7eb 100%);
            color: #334155;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: linear-gradient(135deg, #4caf50 0%, #81c784 100%);
            color: white;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            box-shadow: 0 4px 20px rgba(76, 175, 80, 0.2);
        }

        .header h1 {
            font-size: 24px;
            font-weight: 600;
            display: flex;
            align-items: center;
        }

        .header h1::before {
            content: "🌱";
            margin-right: 10px;
            font-size: 28px;
        }

        .actions-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .search-form {
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            font-size: 14px;
            margin-bottom: 5px;
            color: #2e7d32;
            font-weight: 500;
        }

        .form-control {
            padding: 8px 12px;
            border: 1px solid #c8e6c9;
            border-radius: 6px;
            font-size: 14px;
            transition: all 0.3s ease;
            background-color: white;
            outline: none;
        }

        .form-control:focus {
            border-color: #4caf50;
            box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
        }

        .btn-primary {
            background-color: #4caf50;
            color: white;
        }

        .btn-primary:hover {
            background-color: #388e3c;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(56, 142, 60, 0.3);
        }

        .btn-secondary {
            background-color: #81c784;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #66bb6a;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(102, 187, 106, 0.3);
        }

        .btn-danger {
            background-color: #f44336;
            color: white;
        }

        .btn-danger:hover {
            background-color: #d32f2f;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(211, 47, 47, 0.3);
        }

        .btn-warning {
            background-color: #ff9800;
            color: white;
        }

        .btn-warning:hover {
            background-color: #f57c00;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(245, 124, 0, 0.3);
        }

        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            padding: 20px;
            margin-bottom: 20px;
        }

        .table-container {
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        .data-table th, .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }

        .data-table th {
            background-color: #f1f8e9;
            color: #2e7d32;
            font-weight: 600;
            position: sticky;
            top: 0;
        }

        .data-table tr:hover {
            background-color: #f5f5f5;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-active {
            background-color: #e8f5e9;
            color: #2e7d32;
        }

        .status-inactive {
            background-color: #ffebee;
            color: #c62828;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 20px;
        }

        .page-info {
            color: #555;
            font-size: 14px;
        }

        .pagination a {
            padding: 6px 12px;
            border-radius: 4px;
            background-color: #f1f8e9;
            color: #2e7d32;
            text-decoration: none;
            transition: all 0.3s ease;
        }

        .pagination a:hover {
            background-color: #c8e6c9;
        }

        .pagination a.active {
            background-color: #4caf50;
            color: white;
        }

        .pagination a.disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .device-icon {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            object-fit: cover;
            margin-right: 10px;
        }

        .device-info {
            display: flex;
            align-items: center;
        }

        .device-details {
            display: flex;
            flex-direction: column;
        }

        .device-name {
            font-weight: 500;
            color: #2e7d32;
        }

        .device-type {
            font-size: 12px;
            color: #666;
        }

        .action-buttons {
            display: flex;
            gap: 5px;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .empty-state-icon {
            font-size: 48px;
            margin-bottom: 10px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }

            .actions-bar {
                flex-direction: column;
                align-items: stretch;
            }

            .search-form {
                flex-direction: column;
                align-items: stretch;
                width: 100%;
            }

            .form-group {
                width: 100%;
            }

            .data-table th, .data-table td {
                padding: 8px;
                font-size: 14px;
            }

            .device-info {
                flex-direction: column;
                align-items: flex-start;
            }

            .action-buttons {
                flex-wrap: wrap;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>设备管理</h1>
    </div>

    <div class="actions-bar">
        <div class="search-form">
            <div class="form-group">
                <label for="devName">设备名称</label>
                <input type="text" id="devName" name="devName" class="form-control" placeholder="输入设备名称">
            </div>
            <div class="form-group">
                <label for="devType">设备类型</label>
                <select id="devType" name="devType" class="form-control">
                    <option value="">全部类型</option>
                    <option value="灌溉设备">灌溉设备</option>
                    <option value="监测设备">监测设备</option>
                    <option value="气象设备">气象设备</option>
                </select>
            </div>
            <div class="form-group" style="justify-content: flex-end;">
                <button type="button" class="btn btn-primary" onclick="searchDevices()">
                    <span>🔍</span> 查询
                </button>
            </div>
        </div>
        <button type="button" class="btn btn-primary" onclick="addDevice()">
            <span>➕</span> 添加设备
        </button>
    </div>

    <div class="card">
        <div class="table-container">
            <table class="data-table" id="deviceTable">
                <thead>
                    <tr>
                        <th>设备信息</th>
                        <th>设备类型</th>
                        <th>位置</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="deviceTableBody">
                    <!-- 设备数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
            <div id="emptyState" class="empty-state" style="display: none;">
                <div class="empty-state-icon">📦</div>
                <p>暂无设备数据</p>
            </div>
        </div>

        <div class="pagination" id="pagination">
            <!-- 分页控件将通过JavaScript动态生成 -->
        </div>
    </div>
</div>

<script>
    // 全局变量
    let currentPage = 1;
    const pageSize = 10;
    let totalDevices = 0;

    // 获取设备图标
    function getDeviceIcon(deviceType, iconName) {
        // 如果有icon_name，优先使用
        if (iconName && iconMap[iconName]) {
            return iconMap[iconName];
        }
        
        // 否则根据设备类型返回默认图标
        switch(deviceType) {
            case '灌溉设备':
                return '💧';
            case '监测设备':
                return '🌡️';
            case '气象设备':
                return '🌤️';
            default:
                return '📦';
        }
    }

    // 获取设备图标颜色
    function getDeviceIconColor(deviceType) {
        switch(deviceType) {
            case '灌溉设备':
                return '#2196F3';
            case '监测设备':
                return '#4CAF50';
            case '气象设备':
                return '#FF9800';
            default:
                return '#9E9E9E';
        }
    }

    // 图标映射
    const iconMap = {
        'irrigation.png': '💧',
        'soil_sensor.png': '🌡️',
        'weather_station.png': '🌤️',
        'pest_monitor.png': '🐛'
    };
    
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 输出图标数据到控制台
        console.log('可用图标列表:', iconMap);
        loadDevices();
    });

    // 加载设备数据
    function loadDevices() {
        const devName = document.getElementById('devName').value;
        const devType = document.getElementById('devType').value;

        // 设置请求头，表明这是AJAX请求
        const headers = new Headers();
        headers.append('X-Requested-With', 'XMLHttpRequest');

        // 发送AJAX请求获取设备数据
        fetch('deviceServlet?actionType=doQueryDev&devName=' + encodeURIComponent(devName) + 
              '&devType=' + encodeURIComponent(devType) + 
              '&currentPage=' + currentPage + '&pageSize=' + pageSize + '&format=json', {
            method: 'GET',
            headers: headers
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应异常');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    renderDeviceTable(data.devices);
                    renderPagination(data.totalCount);
                } else {
                    console.error('加载设备数据失败:', data.message);
                    showEmptyState();
                }
            })
            .catch(error => {
                console.error('请求失败:', error);
                showEmptyState();
            });
    }

    // 渲染设备表格
    function renderDeviceTable(devices) {
        const tableBody = document.getElementById('deviceTableBody');
        const emptyState = document.getElementById('emptyState');
        const deviceTable = document.getElementById('deviceTable');

        if (!devices || devices.length === 0) {
            showEmptyState();
            return;
        }

        emptyState.style.display = 'none';
        deviceTable.style.display = 'table';

        let html = '';
        devices.forEach(device => {
            const statusClass = device.is_valid === '1' || device.is_valid === 'Y' ? 'status-active' : 'status-inactive';
            const statusText = device.is_valid === '1' || device.is_valid === 'Y' ? '启用' : '未启用';

            html += `
                <tr>
                    <td>
                        <div class="device-info">
                            <div class="device-icon" style="background-color: ${getDeviceIconColor(device.dev_type)}; display: flex; align-items: center; justify-content: center; color: white; font-size: 20px;">
                                ${getDeviceIcon(device.dev_type, device.icon_name)}
                            </div> 

                            <div class="device-details">
                                <div class="device-name">${device.dev_name}</div>
                                <div class="device-type">ID: ${device.dev_id}</div>
                            </div>
                        </div>
                    </td>
                    <td>${device.dev_type}</td>
                    <td>${device.lat}, ${device.lon}</td>
                    <td><span class="status-badge ${statusClass}">${statusText}</span></td>
                    <td>
                        <div class="action-buttons">
                            <button type="button" class="btn btn-warning" onclick="editDevice(${device.dev_id})">
                                <span>✏️</span> 编辑
                            </button>
                            <button type="button" class="btn btn-danger" onclick="deleteDevice(${device.dev_id})">
                                <span>🗑️</span> 删除
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        });

        tableBody.innerHTML = html;
    }

    // 显示空状态
    function showEmptyState() {
        document.getElementById('emptyState').style.display = 'block';
        document.getElementById('deviceTable').style.display = 'none';
    }

    // 渲染分页控件
    function renderPagination(totalCount) {
        const pagination = document.getElementById('pagination');
        totalDevices = totalCount;

        const totalPages = Math.ceil(totalCount / pageSize);

        let html = `
            <div class="page-info">共 ${totalCount} 条记录，当前第 ${currentPage} 页 / 共 ${totalPages} 页</div>
        `;

        // 首页
        html += `<a href="#" onclick="goToPage(1)" ${currentPage == 1 ? 'class="disabled"' : ''}>首页</a>`;

        // 上一页
        html += `<a href="#" onclick="goToPage(${currentPage - 1})" ${currentPage == 1 ? 'class="disabled"' : ''}>上一页</a>`;

        // 页码
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        for (let i = startPage; i <= endPage; i++) {
            html += `<a href="#" onclick="goToPage(${i})" ${i == currentPage ? 'class="active"' : ''}>${i}</a>`;
        }

        // 下一页
        html += `<a href="#" onclick="goToPage(${currentPage + 1})" ${currentPage == totalPages ? 'class="disabled"' : ''}>下一页</a>`;

        // 尾页
        html += `<a href="#" onclick="goToPage(${totalPages})" ${currentPage == totalPages ? 'class="disabled"' : ''}>尾页</a>`;

        // 跳转
        html += `
            <div class="form-group" style="display: flex; flex-direction: row; align-items: center;">
                <label for="gotoPage" style="margin-right: 5px;">跳转到</label>
                <input type="number" id="gotoPage" class="form-control" style="width: 60px; margin-right: 5px;" value="${currentPage}" min="1" max="${totalPages}">
                <button type="button" class="btn btn-secondary" onclick="goToPageInput()">跳转</button>
            </div>
        `;

        pagination.innerHTML = html;
    }

    // 跳转到指定页
    function goToPage(page) {
        const totalPages = Math.ceil(totalDevices / pageSize);

        if (page < 1 || page > totalPages) {
            return;
        }

        currentPage = page;
        loadDevices();
    }

    // 通过输入框跳转页码
    function goToPageInput() {
        const gotoPage = parseInt(document.getElementById('gotoPage').value);
        goToPage(gotoPage);
    }

    // 搜索设备
    function searchDevices() {
        currentPage = 1;
        loadDevices();
    }

    // 添加设备
    function addDevice() {
        window.location.href = 'dev_add.jsp';
    }

    // 编辑设备
    function editDevice(devId) {
        window.location.href = `dev_edit.jsp?devId=${devId}`;
    }

    // 删除设备
    function deleteDevice(devId) {
        if (confirm('确定要删除此设备吗？')) {
            // 设置请求头，表明这是AJAX请求
            const headers = new Headers();
            headers.append('X-Requested-With', 'XMLHttpRequest');

            fetch('deviceServlet?actionType=doDeleteDev&devId=' + devId + '&format=json', {
                method: 'GET',
                headers: headers
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        alert('设备删除成功');
                        loadDevices();
                    } else {
                        alert('设备删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('删除设备失败:', error);
                    alert('设备删除失败，请稍后再试');
                });
        }
    }
</script>
</body>
</html>
